<script>

export default {

  name: "Main",
  data() {
    return {
      tableData: [],
      pagenum: 1,
      pageSize: 10,
      total: 0,
      name: '',
      sex: '',
      sexs: [
        {value: '1', label: '男'},
        {value: '0', label: '女'}
      ],
      centerDialogVisible: false, // 添加对话框显示状态变量
      form: {
        no: '',
        password: '',
        name: '',
        age: '',
        sex: '1',
        phone: ''
      },

    };
  },
  created() {
    this.loadPost();
  },
  methods: {
    loadPost() {
      this.$axios.post(this.$httpUrl + '/user/listPage', {
        pageNum: this.pagenum,
        pageSize: this.pageSize,
        param: {
          name: this.name,
          sex: this.sex
        }
      })
          .then(res => {
            if (res && res.data) {
              if (Array.isArray(res.data.data)) {
                this.tableData = res.data.data;
                this.total = res.data.total || 0;
              } else {
                console.error('API返回格式不符合预期:', res);
                this.tableData = [];
              }
            } else {
              console.error('API响应为空或格式错误:', res);
              this.tableData = [];
            }
          })
          .catch(error => {
            console.error('获取数据失败:', error);
            this.tableData = [];
          });
    }
    ,
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.loadPost();
    }
    ,
    handleCurrentChange(newPage) {
      this.pagenum = newPage;
      this.loadPost();
    }
    ,

    // 重置按钮
    resetParam() {
      this.name = '';
      this.sex = '';
      this.loadPost();
    },
    // 添加新用户
    add() {
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        this.resetFrom()
      })
    },
    doMod() {
      this.$axios.post(this.$httpUrl + '/user/updata', this.form).then(res => res.data).then(res => {
        // console.log(res)
        if (res.code == 0) {
          if (this.form.id) {
            this.doMod();
          } else {
            this.doSave();
          }
          this.$message({
            message: '操作成功！',
            type: 'success'
          })
          this.centerDialogVisible = false
          this.loadPost()
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          })
        }
      })
    },
    save() {
      if (this.form.id) {
        this.updateUser();
      } else {
        this.saveUser();
      }
    },
    saveUser() {
      this.$axios.post(this.$httpUrl + '/user/save', this.form).then(res => res.data).then(res => {
        if (res.code === 0) {
          this.$message({
            message: '新增用户成功！',
            type: 'success'
          });
          this.centerDialogVisible = false;
          this.loadPost();
        } else {
          this.$message({
            message: '新增用户失败！',
            type: 'error'
          });
        }
      }).catch(error => {
        console.error('保存用户失败:', error);
        this.$message.error('保存用户请求失败');
      });
    },

    handleEdit(row) {
      console.log(row)

      this.form.id = row.id
      this.form.no = row.no
      this.form.password = ''
      this.form.name = row.name
      this.form.age = row.age + ''
      this.form.sex = row.sex + ''
      this.form.phone = row.phone
      this.form.roleId = row.roleId

      this.centerDialogVisible = true


    },
    handleDelete(index, row) {
      // 弹出确认对话框
      this.$confirm('确定要删除该用户吗？删除后将无法恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        // 调用后端接口删除用户
        this.$axios.post(this.$httpUrl + '/user/delete', {id: row.id})
            .then(res => {
              if (res && res.data && res.data.code === 0) {
                this.$message.success('删除用户成功');
                // 刷新列表
                this.loadPost();
              } else {
                this.$message.error('删除用户失败: ' + (res.data.msg || '未知错误'));
                console.error('API响应错误:', res);
              }
            })
            .catch(error => {
              this.$message.error('删除用户请求失败');
              console.error('请求错误:', error);
            });
      }).catch(() => {
        // 用户取消操作
      });
    },
    resetFrom() {
      this.$refs.form.resetFields();
    }
  }
}
</script>

<template>
  <div style="margin: 5px">
    <!--    查询框-->
    <el-input
        style="width: 200px"
        placeholder="请输入名字"
        v-model="name"
        @keyup.enter="loadPost()"
    />
    <!--    多选框查询-->
    <el-select
        v-model="sex"
        placeholder="选择性别"
        style="width: 200px;margin-left: 6px"
    >
      <el-option
          v-for="item in sexs"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>

    <el-button type="primary" style="margin-left: 6px" @click="loadPost">查询</el-button>
    <el-button type="success" @click="resetParam">重置</el-button>
    <el-button type="info" style="margin-left: 5px;" @click="add">
      新增
      <el-icon class="el-icon--right">
        <Upload/>
      </el-icon>
    </el-button>
  </div>


  <div>
    <el-table
        :data="tableData"
        style="width: 100%; height: 100%"
        :header-cell-style="{ background: '#dcdfe6'}"
        border
    >
      <el-table-column prop="id" label="ID" width="60" he></el-table-column>
      <el-table-column prop="no" label="账号" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>

      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.sex === 1 ? '男' : '女' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="roleId" label="角色" width="100">
        <template #default="scope">
          <el-tag
              :type="scope.row.roleId === 0 ? 'danger' : 'success'"
              effect="dark"
          >
            {{ scope.row.roleId === 0 ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
      <el-dialog
          v-model="centerDialogVisible"
          title="添加新用户"
          width="30%"
          center
      >
        <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
          <el-form
              :model="form"
              label-width="80px"
              style="width: 100%; text-align: left;"
              ref="form"
          >
            <!-- 账号 -->
            <el-form-item label="账号" prop="no">
              <el-input v-model="form.no" style="width: 100%;"/>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" style="width: 100%;"/>
            </el-form-item>

            <!-- 姓名 -->
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" style="width: 100%;"/>
            </el-form-item>

            <!-- 年龄 -->
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" type="number" style="width: 100%;"/>
            </el-form-item>

            <!-- 性别 -->
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex" style="width: 100%;">
                <el-radio :value="1">男</el-radio>
                <el-radio :value="0">女</el-radio>
              </el-radio-group>
            </el-form-item>


            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" style="width: 100%;"/>
            </el-form-item>
          </el-form>
        </div>

        <div class="dialog-footer" style="text-align: center; padding: 10px;">
          <el-button @click="centerDialogVisible = false" style="margin-right: 10px;">取消</el-button>
          <el-button @click="save()" type="primary">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>


</template>

<style>

</style>